/* global $, fs */
import "zx/globals";

// 1. Determine packages updated
const gitStatus = await $`git status --porcelain`;
const changedFiles = gitStatus.stdout
  .split("\n")
  .filter((l) => l.startsWith(" M ") || l.startsWith("M  "))
  .map((line) => line.substring(3));
changedFiles.sort();

const changedPackages = changedFiles.filter((file) =>
  file.endsWith("/package.json"),
);

const toCommit = [".changeset/pre.json"];

const releasedPackages = [];

// 2. For each package, update the `version.ts` file
for (const packageJsonPath of changedPackages) {
  toCommit.push(packageJsonPath);
  const changelogPath = packageJsonPath.replace(
    /package\.json$/,
    "CHANGELOG.md",
  );
  toCommit.push(changelogPath);
  const versionTsPath = packageJsonPath.replace(
    /package\.json$/,
    "src/version.ts",
  );

  const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
  if (packageJson.private) {
    continue;
  }

  releasedPackages.push(`${packageJson.name}@${packageJson.version}`);

  if (await fs.exists(versionTsPath)) {
    await fs.writeFile(
      versionTsPath,
      `\
// This file is autogenerated by /scripts/postversion.mjs
export const version = ${JSON.stringify(packageJson.version)};
`,
    );
    toCommit.push(versionTsPath);
  }
}

releasedPackages.sort();

// 3. run yarn
await $`yarn`;
await $`git add yarn.lock`;

// 4. Commit changes (including `.changeset/pre.json`) with helpful commit message
await $`git add ${toCommit}`;
const commitMessage = `\
RELEASING: Releasing ${releasedPackages.length} package(s)

Releases:
${releasedPackages.map((p) => `  ${p}`).join("\n")}

[skip ci]
`;
await $`git commit -m ${commitMessage}`;
